package platform;

import java.util.HashMap;
import io.PacketLikePhoton;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.future.IoFutureListener;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import protocol.OpCode;
import protocol.ReturnCode;

class ConnectListener implements IoFutureListener<ConnectFuture>{
	protected static final Logger log = LoggerFactory.getLogger(ConnectListener.class);
	private NioSocketConnector conn;
	private String serverkey;
	public ConnectListener(NioSocketConnector con,String k)
	{
		conn = con;
		serverkey = k;
	}
    public void operationComplete(ConnectFuture future) {
        if (future.isConnected()) {
        	IoSession curSession = future.getSession();
        	LogicServerConnect.logicServersSessions.put(serverkey, curSession);
        	log.info("IoFutureListener<ConnectFuture> isConnected "
        			+ conn.getDefaultRemoteAddress().getHostString() + ":" + conn.getDefaultRemoteAddress().getPort());
        	
        	HashMap<Short, Object> dicSendHashMap=new HashMap<Short, Object>();
        	dicSendHashMap.put((short)0, serverkey);
        	curSession.write(new PacketLikePhoton(OpCode.SendServerNum, ReturnCode.Yes, "", dicSendHashMap));
        } else {
        	try {
        		future.cancel();
        		
        		LogicServerConnect.logicServersSessions.put(serverkey, null);
        		log.info("IoFutureListener<ConnectFuture> notConnected "
	        			+ conn.getDefaultRemoteAddress().getHostString() + ":" + conn.getDefaultRemoteAddress().getPort());
        		//log.info("current managed conn num:" + conn.getManagedSessionCount());
				Thread.sleep(3000);
				ConnectFuture cf = conn.connect();
	        	cf.addListener(this);
	        	log.info("IoFutureListener<ConnectFuture> reConnecting "
	        			+ conn.getDefaultRemoteAddress().getHostString() + ":" + conn.getDefaultRemoteAddress().getPort());
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
        } 
    }  
}  